/*
 * Copyright (c) 2017.  . All rights reserved.
 */

package com.yiqi.liebang.framework;

import android.app.ActivityManager;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.utils.DynamicTimeFormat;
import com.suozhang.framework.utils.logger.Logger;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.rongim.SealAppContext;
import com.yiqi.liebang.common.rongim.msg.CustomizeMessage;
import com.yiqi.liebang.common.rongim.msg.MyPrivateConversationProvider;
import com.yiqi.liebang.common.rongim.msg.QuestionMessage;
import com.yiqi.liebang.common.rongim.msg.provider.CustomizeMessageItemProvider;
import com.yiqi.liebang.common.rongim.msg.provider.QuestionMessageItemProvider;

import cn.jpush.android.api.JPushInterface;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.push.RongPushClient;


/**
 *
 * @e-mail
 * @date 2017/3/27 14:15
 */

public class LibManager {


    public void init(Context app) {
        //初始化第三方库
        initJPush(app);
        initUM(app);
        initRongIm(app);


        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.window_background, R.color.primary_highlight);//全局设置主题颜色
                return new ClassicsHeader(context).setTimeFormat(new DynamicTimeFormat("更新于 %s"));
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    /**
     * 友盟
     */
    private static void initUM(Context app) {
        UMConfigure.setLogEnabled(AM.isDebug());
        UMConfigure.init(app,"5b769d23f29d980b6e0000f4"
                ,"umeng",UMConfigure.DEVICE_TYPE_PHONE,"");

        PlatformConfig.setWeixin("wxfff2d87111af1d53", "b7e24a8522266b53ed113382789fd29f");
        PlatformConfig.setQQZone("100424468", "c7394704798a158208a74ab60104f0ba");
    }

    /**
     * 极光推送
     */
    private void initJPush(Context app) {
        JPushInterface.setDebugMode(AM.isDebug());    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(app);            // 初始化 JPush
        JPushInterface.stopCrashHandler(app);
        JPushInterface.getRegistrationID(app);

    }

    private static  void initRongIm(Context context){
        /**
         *
         * OnCreate 会被多个进程重入，这段保护代码，确保只有您需要使用 RongIM 的进程和 Push 进程执行了 init。
         * io.rong.push 为融云 push 进程名称，不可修改。
         */
        if (context.getApplicationInfo().packageName.equals(getCurProcessName(context.getApplicationContext()))) {
//            RongPushClient.registerHWPush(context);
//            RongPushClient.registerMiPush(context, "2882303761517873170", "5681787336170");
//            RongPushClient.registerMZPush(context, "1002097", "d4b897f7955a426a9f46c31725db7dc5");
//            try {
//                RongPushClient.registerFCM(context);
//            } catch (RongException e) {
//                e.printStackTrace();
//            }
            /**
             * IMKit SDK调用第一步 初始化
             */
            RongIM.init(context);
            RongContext.init(context);
            SealAppContext.init(context);
            RongIM.getInstance().registerMessageType(CustomizeMessage.class);
            RongIM.getInstance().registerMessageTemplate(new CustomizeMessageItemProvider());

            RongIM.getInstance().registerMessageType(QuestionMessage.class);
            RongIM.getInstance().registerMessageTemplate(new QuestionMessageItemProvider());

            RongIM.getInstance().registerConversationTemplate(new MyPrivateConversationProvider());

            RongIM.setConnectionStatusListener(new RongIMClient.ConnectionStatusListener() {
                @Override
                public void onChanged(ConnectionStatus status) {
                    if (status == ConnectionStatus.TOKEN_INCORRECT) {
                        if (AM.user().isLogin()){
                            String cacheToken=AM.user().getLoginResultCache().getRongCloudToken();
                            if (!TextUtils.isEmpty(cacheToken)) {
                                RongIM.connect(cacheToken, SealAppContext.getInstance().getConnectCallback());
                            } else {
                                Logger.e("seal", "token is empty, can not reconnect");
                            }
                        }else {
                            Logger.e("seal", "token is empty, can not reconnect");
                        }

                    }
                }
            });
        }


    }


    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return
     */
    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {

                return appProcess.processName;
            }
        }
        return null;
    }


}
